package com.tianhui.consignortwofei.utils.download;

/**
 * @author fei
 * @date 2024/6/18
 * @description
 */
import com.fgs.common.manager.CommonSharedPreferenceManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileDownloaderFei {
    public static void downloadFile(String url, String savePath, FeiFileDownloadListener listener) {
        String token = CommonSharedPreferenceManager.getInstance().getToken();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .addHeader("Authorization",token)
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onDownloadFailed(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    saveFile(response, savePath);
                    listener.onDownloadCompleted();
                } else {
                    listener.onDownloadFailed(response.message());
                }
            }
        });
    }

    private static void saveFile(Response response, String savePath) {
        try {
            File file = new File(savePath);
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(response.body().bytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

